// 游戏状态管理
class EggQueueGame {
    constructor() {
        this.queue = [];
        this.score = 0;
        this.level = 1;
        this.timeLeft = 60;
        this.isPlaying = false;
        this.isPaused = false;
        this.maxQueueSize = 10;
        this.timerInterval = null;
        
        // 蛋仔类型配置
        this.eggTypes = {
            normal: { emoji: '🥚', points: 10, color: 'normal' },
            golden: { emoji: '🌟', points: 50, color: 'golden' },
            rainbow: { emoji: '🌈', points: 100, color: 'rainbow' }
        };
        
        this.initializeGame();
        this.bindEvents();
    }
    
    // 初始化游戏
    initializeGame() {
        this.updateDisplay();
        this.updatePreview();
    }
    
    // 绑定事件
    bindEvents() {
        // 游戏控制按钮
        document.getElementById('start-game').addEventListener('click', () => this.startGame());
        document.getElementById('pause-game').addEventListener('click', () => this.pauseGame());
        document.getElementById('reset-game').addEventListener('click', () => this.resetGame());
        
        // 队列控制按钮
        document.getElementById('add-egg').addEventListener('click', () => this.addEgg());
        document.getElementById('remove-egg').addEventListener('click', () => this.removeEgg());
        document.getElementById('clear-queue').addEventListener('click', () => this.clearQueue());
        
        // 蛋仔类型选择
        document.querySelectorAll('input[name="egg-type"]').forEach(radio => {
            radio.addEventListener('change', () => this.updatePreview());
        });
        
        // 重新开始按钮
        document.getElementById('restart-btn').addEventListener('click', () => {
            this.hideGameOverModal();
            this.resetGame();
            this.startGame();
        });
        
        // 点击蛋仔移除
        document.getElementById('queue').addEventListener('click', (e) => {
            if (e.target.classList.contains('egg')) {
                this.removeSpecificEgg(e.target);
            }
        });
    }
    
    // 开始游戏
    startGame() {
        if (this.isPlaying) return;
        
        this.isPlaying = true;
        this.isPaused = false;
        document.getElementById('start-game').disabled = true;
        document.getElementById('pause-game').disabled = false;
        
        this.startTimer();
        this.showMessage('游戏开始！祝你好运！', 'success');
    }
    
    // 暂停游戏
    pauseGame() {
        if (!this.isPlaying || this.isPaused) return;
        
        this.isPaused = true;
        clearInterval(this.timerInterval);
        document.getElementById('pause-game').textContent = '继续游戏';
        this.showMessage('游戏暂停', 'warning');
    }
    
    // 继续游戏
    resumeGame() {
        if (!this.isPlaying || !this.isPaused) return;
        
        this.isPaused = false;
        this.startTimer();
        document.getElementById('pause-game').textContent = '暂停游戏';
        this.showMessage('游戏继续', 'info');
    }
    
    // 重置游戏
    resetGame() {
        this.isPlaying = false;
        this.isPaused = false;
        this.score = 0;
        this.level = 1;
        this.timeLeft = 60;
        this.queue = [];
        
        clearInterval(this.timerInterval);
        
        document.getElementById('start-game').disabled = false;
        document.getElementById('pause-game').disabled = true;
        document.getElementById('pause-game').textContent = '暂停游戏';
        
        this.updateDisplay();
        this.renderQueue();
        this.hideGameOverModal();
        this.showMessage('游戏已重置', 'info');
    }
    
    // 计时器
    startTimer() {
        this.timerInterval = setInterval(() => {
            if (!this.isPaused) {
                this.timeLeft--;
                this.updateDisplay();
                
                // 检查游戏结束
                if (this.timeLeft <= 0) {
                    this.endGame();
                }
                
                // 随机移除蛋仔（模拟服务完成）
                if (Math.random() < 0.1 && this.queue.length > 0) {
                    this.removeEgg();
                    this.addScore(20); // 服务完成奖励
                }
            }
        }, 1000);
    }
    
    // 添加蛋仔到队列
    addEgg() {
        if (!this.isPlaying || this.isPaused) {
            this.showMessage('请先开始游戏！', 'warning');
            return;
        }
        
        if (this.queue.length >= this.maxQueueSize) {
            this.showMessage('队列已满！', 'error');
            return;
        }
        
        const selectedType = document.querySelector('input[name="egg-type"]:checked').value;
        const eggConfig = this.eggTypes[selectedType];
        
        const egg = {
            id: Date.now(),
            type: selectedType,
            emoji: eggConfig.emoji,
            points: eggConfig.points,
            color: eggConfig.color,
            arrivalTime: Date.now()
        };
        
        this.queue.push(egg);
        this.addScore(eggConfig.points);
        this.renderQueue();
        this.updateDisplay();
        
        // 检查升级
        this.checkLevelUp();
        
        this.showMessage(`添加了${this.getTypeName(selectedType)}！+${eggConfig.points}分`, 'success');
    }
    
    // 移除最后一个蛋仔
    removeEgg() {
        if (this.queue.length === 0) {
            this.showMessage('队列是空的！', 'warning');
            return;
        }
        
        const removedEgg = this.queue.pop();
        this.renderQueue();
        this.updateDisplay();
        
        this.showMessage(`移除了${this.getTypeName(removedEgg.type)}`, 'info');
    }
    
    // 移除特定蛋仔
    removeSpecificEgg(eggElement) {
        const eggId = parseInt(eggElement.dataset.eggId);
        const eggIndex = this.queue.findIndex(egg => egg.id === eggId);
        
        if (eggIndex !== -1) {
            const removedEgg = this.queue.splice(eggIndex, 1)[0];
            this.renderQueue();
            this.updateDisplay();
            
            // 移除动画
            eggElement.classList.add('fade-out');
            setTimeout(() => {
                this.showMessage(`移除了${this.getTypeName(removedEgg.type)}`, 'info');
            }, 300);
        }
    }
    
    // 清空队列
    clearQueue() {
        if (this.queue.length === 0) {
            this.showMessage('队列已经是空的！', 'warning');
            return;
        }
        
        const count = this.queue.length;
        this.queue = [];
        this.renderQueue();
        this.updateDisplay();
        
        this.showMessage(`清空了${count}个蛋仔`, 'info');
    }
    
    // 渲染队列
    renderQueue() {
        const queueContainer = document.getElementById('queue');
        queueContainer.innerHTML = '';
        
        this.queue.forEach((egg, index) => {
            const eggElement = document.createElement('div');
            eggElement.className = `egg ${egg.color} fade-in`;
            eggElement.textContent = egg.emoji;
            eggElement.dataset.eggId = egg.id;
            eggElement.title = `${this.getTypeName(egg.type)} - ${egg.points}分`;
            
            // 添加等待时间显示
            const waitTime = Math.floor((Date.now() - egg.arrivalTime) / 1000);
            eggElement.title += `\n等待时间: ${waitTime}秒`;
            
            queueContainer.appendChild(eggElement);
        });
    }
    
    // 更新预览
    updatePreview() {
        const selectedType = document.querySelector('input[name="egg-type"]:checked').value;
        const eggConfig = this.eggTypes[selectedType];
        const previewElement = document.querySelector('.preview-egg');
        
        previewElement.textContent = eggConfig.emoji;
        previewElement.className = `preview-egg ${eggConfig.color}`;
    }
    
    // 更新显示
    updateDisplay() {
        document.getElementById('score').textContent = this.score;
        document.getElementById('level').textContent = this.level;
        document.getElementById('timer').textContent = this.timeLeft;
        document.getElementById('queue-count').textContent = this.queue.length;
        
        // 时间警告
        if (this.timeLeft <= 10) {
            document.getElementById('timer').style.color = 'red';
            document.getElementById('timer').style.fontWeight = 'bold';
        } else {
            document.getElementById('timer').style.color = '';
            document.getElementById('timer').style.fontWeight = '';
        }
    }
    
    // 添加分数
    addScore(points) {
        this.score += points;
        this.updateDisplay();
    }
    
    // 检查升级
    checkLevelUp() {
        const requiredScore = this.level * 200;
        if (this.score >= requiredScore) {
            this.level++;
            this.timeLeft += 30; // 升级奖励时间
            this.showMessage(`恭喜升级到第${this.level}关！+30秒时间奖励`, 'success');
        }
    }
    
    // 结束游戏
    endGame() {
        this.isPlaying = false;
        clearInterval(this.timerInterval);
        
        this.showGameOverModal();
    }
    
    // 显示游戏结束模态框
    showGameOverModal() {
        document.getElementById('final-score').textContent = this.score;
        document.getElementById('final-level').textContent = this.level;
        document.getElementById('game-over-modal').classList.remove('hidden');
    }
    
    // 隐藏游戏结束模态框
    hideGameOverModal() {
        document.getElementById('game-over-modal').classList.add('hidden');
    }
    
    // 获取蛋仔类型名称
    getTypeName(type) {
        const names = {
            normal: '普通蛋仔',
            golden: '黄金蛋仔',
            rainbow: '彩虹蛋仔'
        };
        return names[type] || '未知蛋仔';
    }
    
    // 显示消息
    showMessage(message, type = 'info') {
        // 创建消息元素
        const messageDiv = document.createElement('div');
        messageDiv.className = `game-message ${type}`;
        messageDiv.textContent = message;
        
        // 设置样式
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            padding: 15px 30px;
            border-radius: 25px;
            font-weight: bold;
            z-index: 2000;
            animation: slideDown 0.5s ease-out;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
        `;
        
        // 设置颜色
        const colors = {
            success: 'linear-gradient(135deg, #28a745, #218838)',
            error: 'linear-gradient(135deg, #dc3545, #c82333)',
            warning: 'linear-gradient(135deg, #ffc107, #e0a800)',
            info: 'linear-gradient(135deg, #17a2b8, #138496)'
        };
        
        messageDiv.style.background = colors[type] || colors.info;
        messageDiv.style.color = type === 'warning' ? '#333' : 'white';
        
        // 添加到页面
        document.body.appendChild(messageDiv);
        
        // 自动移除
        setTimeout(() => {
            messageDiv.classList.add('fade-out');
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.parentNode.removeChild(messageDiv);
                }
            }, 500);
        }, 3000);
    }
}

// 音效管理
class SoundManager {
    constructor() {
        this.audioContext = null;
        this.enabled = true;
        this.initializeAudio();
    }
    
    initializeAudio() {
        try {
            window.AudioContext = window.AudioContext || window.webkitAudioContext;
            this.audioContext = new AudioContext();
        } catch (e) {
            console.log('音频上下文初始化失败');
            this.enabled = false;
        }
    }
    
    playSound(frequency, duration, type = 'sine') {
        if (!this.enabled || !this.audioContext) return;
        
        try {
            const oscillator = this.audioContext.createOscillator();
            const gainNode = this.audioContext.createGain();
            
            oscillator.connect(gainNode);
            gainNode.connect(this.audioContext.destination);
            
            oscillator.frequency.value = frequency;
            oscillator.type = type;
            
            gainNode.gain.setValueAtTime(0.3, this.audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, this.audioContext.currentTime + duration);
            
            oscillator.start(this.audioContext.currentTime);
            oscillator.stop(this.audioContext.currentTime + duration);
        } catch (e) {
            console.log('音效播放失败:', e);
        }
    }
    
    playAddEgg() {
        this.playSound(523, 0.1); // C5
        setTimeout(() => this.playSound(659, 0.1), 50); // E5
    }
    
    playRemoveEgg() {
        this.playSound(392, 0.2); // G4
    }
    
    playLevelUp() {
        this.playSound(523, 0.1); // C5
        setTimeout(() => this.playSound(659, 0.1), 100); // E5
        setTimeout(() => this.playSound(784, 0.2), 200); // G5
    }
    
    playGameOver() {
        this.playSound(330, 0.2); // E4
        setTimeout(() => this.playSound(294, 0.2), 200); // D4
        setTimeout(() => this.playSound(262, 0.4), 400); // C4
    }
}

// 添加消息动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideDown {
        from {
            transform: translateX(-50%) translateY(-100px);
            opacity: 0;
        }
        to {
            transform: translateX(-50%) translateY(0);
            opacity: 1;
        }
    }
    
    .game-message {
        font-family: 'Arial', sans-serif;
        text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
    }
`;
document.head.appendChild(style);

// 初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    const game = new EggQueueGame();
    const soundManager = new SoundManager();
    
    // 全局音效访问
    window.game = game;
    window.soundManager = soundManager;
    
    // 为游戏方法添加音效
    const originalAddEgg = game.addEgg.bind(game);
    game.addEgg = function() {
        const result = originalAddEgg();
        if (window.game.isPlaying) {
            soundManager.playAddEgg();
        }
        return result;
    };
    
    const originalRemoveEgg = game.removeEgg.bind(game);
    game.removeEgg = function() {
        const result = originalRemoveEgg();
        soundManager.playRemoveEgg();
        return result;
    };
    
    const originalCheckLevelUp = game.checkLevelUp.bind(game);
    game.checkLevelUp = function() {
        const oldLevel = game.level;
        originalCheckLevelUp();
        if (game.level > oldLevel) {
            soundManager.playLevelUp();
        }
    };
    
    const originalEndGame = game.endGame.bind(game);
    game.endGame = function() {
        soundManager.playGameOver();
        return originalEndGame();
    };
});